#!/usr/bin/env python
# import sip
# sip.setapi('QVariant', 2)

from PySide.QtCore import *
from PySide.QtGui import *

import datahandler
import commonfunctions

class CreateLayoutTab(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.parent = parent

        self.addNoteAction = QAction(QIcon(QDir.currentPath() + "/images/go-bottom.png"), "Add Selected Note to Section", self)
        self.delNoteAction = QAction(QIcon(QDir.currentPath() + "/images/go-top.png"), "Remove Selected Note from Section", self)
        self.noteUpAction = QAction(QIcon(QDir.currentPath() + "/images/go-up.png"), "Move Selected Note Up", self)
        self.noteDownAction = QAction(QIcon(QDir.currentPath() + "/images/go-down.png"), "Move Selected Note Down", self)

        self.notetb = QToolBar()
        self.notetb.addAction(self.addNoteAction)
        self.notetb.addAction(self.delNoteAction)
        self.notetb.addSeparator()
        self.notetb.addAction(self.noteDownAction)
        self.notetb.addAction(self.noteUpAction)
        self.notetb.setStyleSheet("QToolBar { border: 0px }")

        for tmpaction in [self.addNoteAction, self.delNoteAction, self.noteDownAction, self.noteUpAction]:
            tmpaction.setEnabled(False)

        self.sectionList = QListWidget()
        self.unusednoteList = QListWidget()
        self.usednoteList = QListWidget()
        self.sectionLabel = QLabel("Sections")
        self.unusedLabel = QLabel("Available Notes")
        self.usedLabel = QLabel("Notes in Selected Section")
        for tmplist in [self.sectionList, self.unusednoteList, self.usednoteList]:
            tmplist.setSelectionMode(QAbstractItemView.SingleSelection)
            tmplist.setAlternatingRowColors(True)
            tmplist.setFrameStyle(QFrame.Panel)
        self.sectionList.setMaximumWidth(200)

        self.sectionBox = QVBoxLayout()
        self.noteBox = QVBoxLayout()
        self.mainBox = QHBoxLayout()
        self.sectionBox.addWidget(self.sectionLabel)
        self.sectionBox.addWidget(self.sectionList)
        self.noteBox.addWidget(self.unusedLabel)
        self.noteBox.addWidget(self.unusednoteList)
        self.noteBox.addWidget(self.notetb)
        self.noteBox.addWidget(self.usedLabel)
        self.noteBox.addWidget(self.usednoteList)
        self.mainBox.addLayout(self.sectionBox)
        self.mainBox.addLayout(self.noteBox)
        self.setLayout(self.mainBox)

        # connect actions
        self.sectionList.itemClicked.connect(self.updateUsedList)
        self.usednoteList.itemClicked.connect(self.updateActions)
        self.unusednoteList.itemClicked.connect(self.updateActions)
        self.addNoteAction.triggered.connect(self.addNote)
        self.delNoteAction.triggered.connect(self.removeNote)
        self.noteDownAction.triggered.connect(self.downNote)
        self.noteUpAction.triggered.connect(self.upNote)

    def updateActions(self):
        if self.sender() is self.usednoteList:
            self.addNoteAction.setEnabled(False)
            for tmpaction in [self.delNoteAction, self.noteDownAction, self.noteUpAction]:
                tmpaction.setEnabled(True)
            if (self.usednoteList.indexFromItem(self.usednoteList.currentItem()).row() + 1) == self.usednoteList.count():
                self.noteDownAction.setEnabled(False)
            if self.usednoteList.indexFromItem(self.usednoteList.currentItem()).row() == 0:
                self.noteUpAction.setEnabled(False)
            if self.unusednoteList.currentItem() is not None:
                self.unusednoteList.currentItem().setSelected(False)
        elif self.sender() is self.unusednoteList:
            self.addNoteAction.setEnabled(True)
            for tmpaction in [self.delNoteAction, self.noteDownAction, self.noteUpAction]:
                tmpaction.setEnabled(False)
            if self.usednoteList.currentItem() is not None:
                self.usednoteList.currentItem().setSelected(False)
        else:
            self.common.displayError("Invalid List", "Invalid List Action. If this error continues, please file a bug report.", "warning")

    def addNote(self):
        if self.sectionList.currentItem() is not None:
            currentsectionid = self.data.sql(self.data.getCurrentSectionId, [self.sectionList.currentItem().text()], 1) # get sectionid
            orderentry = self.data.sql(self.data.getLastOrderNumber, [self.parent.currentcaseid, currentsectionid], 1) # get last ordernumber
            currentnoteid = self.data.sql(self.data.getCurrentNoteId, [self.unusednoteList.currentItem().text()], 1) # get noteid
            self.data.sql(self.data.addSectionNote, [currentsectionid, currentnoteid, (orderentry + 1)], 0) # add note to section as last entry
            self.updateUsedList()
            self.updateUnusedList()
        else:
            self.common.displayError("No Section Selected", "A note can only be added to a Section.  Please select a Section", "warning")

    def removeNote(self):
        if self.sectionList.currentItem() is not None:
            currentsectionid = self.data.sql(self.data.getCurrentSectionId, [self.sectionList.currentItem().text()], 1) # get sectionid        
            currentnoteid = self.data.sql(self.data.getCurrentNoteId, [self.usednoteList.currentItem().text()], 1) # get noteid
            self.data.sql(self.data.delSectionNote, [currentnoteid], 0)
            self.data.sql(self.data.reorderSectionNotes, [self.parent.currentcaseid, currentsectionid], 0)
            self.updateUsedList()
            self.updateUnusedList()
        else:
            self.common.displayError("No Section Selected", "A note can only be removed from a Section. Pleae select a Section", "warning")

    def downNote(self):
        if self.sectionList.currentItem() is not None: # ensure a section has been selected
            currentsectionid = self.data.sql(self.data.getCurrentSectionId, [self.sectionList.currentItem().text()], 1) # get sectionid
            currentnoteid = self.data.sql(self.data.getCurrentNoteId, [self.usednoteList.currentItem().text()], 1) # get current noteid
            self.data.sql(self.data.downSectionNote, [self.parent.currentcaseid, currentsectionid, currentnoteid], 0) # swap the entries in the db.
            self.updateUsedList()

    def upNote(self):
        if self.sectionList.currentItem() is not None: # ensure a section has been selected
            currentsectionid = self.data.sql(self.data.getCurrentSectionId, [self.sectionList.currentItem().text()], 1) # get sectionid
            currentnoteid = self.data.sql(self.data.getCurrentNoteId, [self.usednoteList.currentItem().text()], 1) # get current noteid
            self.data.sql(self.data.upSectionNote, [self.parent.currentcaseid, currentsectionid, currentnoteid], 0) # swap the entries in db
            self.updateUsedList()
    
    def updateLists(self):
        self.updateSectionList()
        self.updateUsedList()
        self.updateUnusedList()

    def updateSectionList(self):
        self.sectionList.clear()
        self.sectionList.addItems(self.data.sql(self.data.updateSectionList, [self.parent.currentcaseid], 1))

    def updateUsedList(self):
        self.usednoteList.clear()
        if self.sectionList.currentItem() is not None:
            currentsectionid = self.data.sql(self.data.getCurrentSectionId, [self.sectionList.currentItem().text()], 1) # get currently selected sectionid
            self.usednoteList.addItems(self.data.sql(self.data.updateUsedNoteList, [self.parent.currentcaseid, currentsectionid], 1))

    def updateUnusedList(self):
        self.unusednoteList.clear()
        self.unusednoteList.addItems(self.data.sql(self.data.updateUnusedNoteList, [self.parent.currentcaseid], 1))
    
    """
        # connect actions
        self.addlayoutAction.triggered.connect(self.addLayout)
        self.propertyAction.triggered.connect(self.editCaption)
        self.addrowAction.triggered.connect(self.addRow)
        self.delrowAction.triggered.connect(self.delRow)
        self.addcolAction.triggered.connect(self.addCol)
        self.delcolAction.triggered.connect(self.delCol)
        self.layoutList.itemSelectionChanged.connect(self.showLayout)
        self.dellayoutAction.triggered.connect(self.delLayout)
        self.updatelayoutAction.triggered.connect(self.updateLayout)
 
    def addLayout(self):
        tmplayoutcaption, ok = QInputDialog.getText(self, "Layout Caption", "Create the Layout Caption:")
        if ok and tmplayoutcaption:
            self.data.opensql()
            self.data.insertLayout(tmplayoutcaption, self.parent.currentcaseid)
            self.data.commitsql()
            self.data.closesql()
            self.updateLayoutList()
            
    def delLayout(self):
        self.checkMessage = QMessageBox.warning(self, "Delete Layout", "Are you sure you want to delete the layout?\n This action cannot be undone.", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if self.checkMessage is QMessageBox.StandardButton.Yes:
            self.data.opensql()
            self.data.deleteLayout(self.parent.currentlayoutid)
            self.data.commitsql()
            self.data.closesql()
            self.updateLayoutList()

    def editCaption(self):
        tmplayoutcaption, ok = QInputDialog.getText(self, "Layout Caption", "Modify the Layout Caption:")
        if ok and tmplayoutcaption:
            self.data.opensql()
            self.data.updateLayoutCaption(self.parent.currentlayoutid, tmplayoutcaption)
            self.data.commitsql()
            self.data.closesql()
            self.updateLayoutList()

    def addRow(self):
        self.layoutEditor.insertRow(self.layoutEditor.currentRow())

    def delRow(self):
        self.layoutEditor.removeRow(self.layoutEditor.currentRow())

    def addCol(self):
        self.layoutEditor.insertColumn(self.layoutEditor.currentColumn())

    def delCol(self):
        self.layoutEditor.removeColumn(self.layoutEditor.currentColumn())

    def updateLayout(self):
        tmpdata = ""
        for i in range(0, self.layoutEditor.rowCount()):
            if(i > 0): tmpdata += "||"
            for j in range(0, self.layoutEditor.columnCount()):
                if(j > 0 and j < self.layoutEditor.columnCount()): tmpdata += "::"
                if self.layoutEditor.item(i, j) is not None:
                    tmpdata += self.layoutEditor.item(i, j).text()
                else:
                    tmpdata += ""
        self.data.opensql()
        self.data.updateLayoutData(tmpdata, self.parent.currentlayoutid)
        self.data.commitsql()
        self.data.closesql()
        self.updateLayoutList()

    def updateLayoutList(self):
        self.layoutList.clear()
        self.layoutList.addItems(self.data.sql(self.data.updateLayoutList, [self.parent.currentcaseid], 1))
        for tmpaction in [self.dellayoutAction, self.addrowAction, self.delrowAction, self.addcolAction, self.delcolAction, self.propertyAction, self.updatelayoutAction]:
            if tmpaction.isEnabled() is True:
                tmpaction.setEnabled(False)
        self.layoutEditor.clear()
        self.layoutEditor.setRowCount(0)
        self.layoutEditor.setColumnCount(0)

    def showLayout(self):
        if self.layoutList.count() > 0:
            self.layoutEditor.clear()
            self.layoutEditor.setRowCount(0)
            self.layoutEditor.setColumnCount(0)
            for tmpaction in [self.dellayoutAction, self.addrowAction, self.delrowAction, self.addcolAction, self.delcolAction, self.propertyAction, self.updatelayoutAction]:
                if tmpaction.isEnabled() is False:
                    tmpaction.setEnabled(True)
            self.currentlayoutdata, self.parent.currentlayoutid = self.data.sql(self.data.getLayoutValuesFromLayoutList, [self.layoutList.currentItem().text(), self.parent.currentcaseid], 1)
            if len(self.currentlayoutdata) > 0:
                self.layoutEditor.setRowCount(len(self.currentlayoutdata))
                self.layoutEditor.setColumnCount(len(self.currentlayoutdata[0]))
                for i in range(0, len(self.currentlayoutdata)):
                    for j in range(0, len(self.currentlayoutdata[i])):
                        self.layoutEditor.setItem(i, j, QLayoutWidgetItem(self.currentlayoutdata[i][j]))
    """
